
import { ApiController, ApiGet, ApiQuery, ApiQueryParam, DataType } from 'xl-ts-plugins/router'
import { getRepository } from 'xl-ts-plugins/typeorm'
import { Photo } from '../entity/Photo'
import { ListParamsModelName, ListParamsQueryBuilder } from '../utils/list-params'
import { ajaxResultSuccess } from '../utils/custom-result'


/**
 * 照片控制器
*/
@ApiController({ path: '/photo', tags: [ 'Photo' ] })
export default class PhotoController {
  @ApiGet({
    path: '/getPhotoList', summary: '获取照片列表',
    responseModel: { type: DataType.ModelArray('Photo') }
  })
  async getPhotoList(
    @ApiQuery({ type: DataType.Model(ListParamsModelName) }) query,
    @ApiQueryParam({ name: 'photoIds', description: '照片 id 数组(用 , 分隔)' }) photoIds
  ) {
    // 列表参数查询
    const sqb = ListParamsQueryBuilder(
      getRepository(Photo).createQueryBuilder('photo'),
      query,
      'photo.create_time'
    )
      .leftJoinAndSelect('photo.author', 'author')
      .leftJoinAndSelect('author.user', 'user')
      .orderBy('photo.create_time', 'ASC')

    // 照片id查询
    if (photoIds && photoIds.length) {
      const photoIdsList = (photoIds as string).split(',')
      sqb.andWhereInIds(photoIdsList)
    }

    const [ list, total ] = await sqb.getManyAndCount()

    return ajaxResultSuccess({ list, total })
  }

  @ApiGet({ path: '/getPhotoCountByAuthor', summary: '获取作者的照片总数' })
  async getPhotoCountByAuthor(
    @ApiQueryParam({ name: 'userId', description: '用户id' }) userId,
    @ApiQueryParam({ name: 'userName', description: '用户名' }) userName
  ) {
    const sqb = getRepository(Photo)
      .createQueryBuilder('photo')
      .select('photo.author_id as authorId')
      .addSelect('user.user_id as userId')
      .addSelect('user.user_name as userName')
      .addSelect('COUNT(*) as count')
      .innerJoin('author', 'author', 'photo.author_id = author.author_id')
      .innerJoin('user', 'user', 'author.user_id = user.user_id')

    userId && sqb.orWhere(`user.user_id = ${userId}`)

    userName && sqb.orWhere(`user.user_name LIKE '%${userName}%'`)

    sqb.groupBy('photo.author_id')

    const result = await sqb.getRawMany()

    return ajaxResultSuccess(result)
  }
}